<?php

namespace App\Models\Youzan;


use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;


/**
 * Class YouzanAuthorizer
 *
 * @property int id
 * @property int $youzan_store_id
 * @property string url
 * @property string $refresh_token
 * @property string $access_token
 * @property Carbon $updated_at
 * @property Carbon $expired_at
 * @property string $expires_in
 *
 * @package App\Models\Youzan
 * @mixin Builder
 */
class YouzanAuthorizer extends Model
{
    use Authorizable;

    protected $table = 'youzan_authorizers';

    protected $guarded = [];

    protected $casts = [
        'expired_at'      => 'date',
        'youzan_store_id' => 'int',
    ];


    /**
     * 有赞refresh 同时更新数据库的token
     *
     * @param array $token
     * @return bool
     */
    public function updateToken(array $token)
    {
       return $this->update([
            'access_token'  => $token['access_token'],
            'expires_in'    => $token['expires_in'],
            'refresh_token' => $token['refresh_token'],
            'scope'         => $token['scope'],
            'token_type'    => $token['token_type'],
            'expired_at'    => now()->addSecond($token['expires_in']),
        ]);
    }

    public function tokenExpiredAt()
    {
        return $this->expired_at;
    }

    public function tokenExpired()
    {
        return $this->expired_at <= now();
    }
}
